import React, { useState, useRef } from "react";
//ref在react体系中保存变量
export default function App() {
  const mytext = useRef();
  const [list, setList] = useState(["初始", "dwd"]);

  const rand1 = Math.floor(Math.random() * 999999 + 1);
  const handleAdd = () => {
    console.log("dawdawd输入值", mytext.current.value);
    let text = mytext.current.value;
    let findeIndex = list.findIndex((item) => {
      return text === item;
    });
    if (findeIndex !== -1) {
      //   setText("");
      alert("输入值已存在，请重新输入！");
      mytext.current.value = "";
      return;
    }
    if (text.trim() === "") {
      //   setText("");
      alert("不能输入空格值，请重新输入！");
      mytext.current.value = "";
      return;
    }
    setList([...list, text]);
    // 输入完清空输入框值
    mytext.current.value = "";
  };
  const handleDelete = (i) => {
    console.log("能删除的下标", i);
    // 不能影响原状态
    var newList = [...list];
    newList.splice(i, 1);
    setList([...newList]);
  };
  return (
    <div>
      <input ref={mytext} />
      <button onClick={handleAdd}>添加</button>

      <ul>
        {list.map((item, index) => (
          <li key={item + rand1}>
            {item}{" "}
            <button
              onClick={() => {
                handleDelete(index);
              }}
            >
              删除Del
            </button>
          </li>
        ))}
      </ul>
      {list.length > 0 ? <span>list数据如上</span> : <h4>暂无待办事项</h4>}
    </div>
  );
}
